/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.platform.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import org.springblade.modules.platform.dto.*;
import org.springblade.modules.platform.entity.*;
import org.springblade.modules.platform.service.*;
import org.springblade.modules.platform.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.vo.DeptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 *  控制器
 *
 * @author BladeX
 * @since 2020-11-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("/service-huateng-sxdb/producttype")
@Api(value = "", tags = "产品接口")
@Slf4j
public class ProductTypeController extends BladeController {
	private final IProductTypeService productTypeService;
	static List<DeviceCategory> collect;

	private final IDeptService iSysClient;
	private final IDeviceTableService iDeviceTableService;

	/**
	 * 递归查询子节点
	 * @param root  根节点
	 * @param all   所有节点
	 * @return 根节点信息
	 */
	 static List<DeviceCategory> getChildrens(DeviceCategory root, List<DeviceCategory> all) {
		List<DeviceCategory> children = all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).map(
			(m) -> {
				m.setChildren(getChildrens(m, all));
				return m;
			}
		).collect(Collectors.toList());
		return children;
	}
	static {
	 	try {
			ClassPathResource resource = new ClassPathResource("device-category.json");
			String json = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
			List<DeviceCategory> deviceCategories = JSON.parseArray(json, DeviceCategory.class);
			//获取父节点
			collect = deviceCategories.stream().filter(m -> m.getParentId() .equals("0")).map(
				(m) -> {
					m.setChildren(getChildrens(m, deviceCategories));
					return m;
				}
			).collect(Collectors.toList());
		}catch (Exception e){
	 		log.error("json转化异常");
		}
	}
	/**
	 * 详情
	 */
	@ApiLog("产品-详情")
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "产品-详情", notes = "传入productType")
	public R<ProductTypeVO> detail(String productId) {
		ProductTypeVO productTypeVO = new ProductTypeVO();
		ProductType detail = productTypeService.getOne(new QueryWrapper<ProductType>().lambda()
			.eq(ProductType::getProductId,productId)
			.eq(ProductType::getIsDeleted,0));
		log.info("detail====：{}",detail);
		Long integer = iDeviceTableService.count(new QueryWrapper<DeviceTable>().lambda()
			.eq(DeviceTable::getProductId, productId)
			.eq(DeviceTable::getIsDeleted, 0));
		BeanUtils.copyProperties(detail,productTypeVO);
		productTypeVO.setEquipmentNumber(integer);
		return R.data(productTypeVO);
	}


	@ApiLog("产品-分页")
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "产品-分页", notes = "传入productType")
	public R<IPage<ProductTypeVO>> list(ProductType productType, Query query) {
		IPage<ProductTypeVO> pages = productTypeService.selectProductTypePage(query, productType);
		return R.data(pages);
	}
	/**
	 * 新增
	 */
	@ApiLog("产品-新增")
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "产品-新增", notes = "传入productType")
	public R save(@Valid @RequestBody ProductTypeDTO productType) {
		BladeUser user = AuthUtil.getUser();
		String productId = productType.getProductId();
		Long count = productTypeService.count(new QueryWrapper<ProductType>().lambda()
			.eq(ProductType::getProductId, productId));
		if(count>0){
			return R.fail("设备编号已存在");
		}
		productType.setUpdateTime(System.currentTimeMillis());
		productType.setInsertTime(System.currentTimeMillis());
		productType.setIsDeleted(0);
		productType.setState(0);
		productType.setCreateUser(user.getUserId());
		return R.status(productTypeService.save(productType));
	}

	/**
	 * 修改
	 */
	@ApiLog("产品-修改")
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "产品-修改", notes = "传入productType")
	public R update(@Valid @RequestBody ProductTypeDTO productType) {
		return R.status(productTypeService.update(productType,new QueryWrapper<ProductType>().lambda().eq(ProductType::getProductId,productType.getProductId())));
	}

	/**
	 * 新增或修改
	 */
	@ApiLog("产品-新增或修改")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "产品-新增或修改", notes = "传入productType")
	public R submit(@Valid @RequestBody ProductType productType) {
		return R.status(productTypeService.saveOrUpdate(productType));
	}

	/**
	 * 删除
	 */
	@ApiLog("产品-删除")
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "产品-删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String productId) {
		ProductType productType = productTypeService.getOne(new QueryWrapper<ProductType>().lambda()
			.eq(ProductType::getProductId, productId));
		productType.setUpdateTime(System.currentTimeMillis());
		productType.setIsDeleted(1);
		List<DeviceTable> list = iDeviceTableService.list(new QueryWrapper<DeviceTable>().lambda()
			.eq(DeviceTable::getProductId, productId)
			.eq(DeviceTable::getIsDeleted, 0));

		if(!CollectionUtils.isEmpty(list)){
			return R.fail("该产品关联设备，请先删除子设备。");
		}
		return R.status(productTypeService.updateById(productType));
	}
	/**
	 * 自定义分页
	 */
	@ApiLog("产品-品类下拉框")
	@GetMapping("/getDeviceCategoryList")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "产品-品类下拉框", notes = "")
	public R<List<DeviceCategory>> getDeviceCategoryList() {
		return R.data(collect);
	}
	/**
	 * 自定义分页
	 */
/*	@ApiLog("产品-添加-消息协议下拉框")
	@GetMapping("/deviceaccessagreementList")
	@ApiOperationSupport(order = 42)
	@ApiOperation(value = "产品-添加-消息协议下拉框", notes = "传入deviceAccessAgreement")
	public R<List<DeviceAccessAgreement>> deviceaccessagreementList() {
		String tenantId = AuthUtil.getTenantId();
		List<DeviceAccessAgreement> deviceAccessAgreementList = iDeviceAccessAgreementServiceClient.getDeviceAccessAgreementList(tenantId);
		return R.data(deviceAccessAgreementList);
	}*/

	/**
	 * 分页 公司表
	 */
	@GetMapping("/tree")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "树", notes = "")
	public R<List<DeptVO>> tree() {
		BladeUser user = AuthUtil.getUser();
		log.info("查询组织机构：{}",user);
		R<List<DeptVO>> deptChildBydept = iSysClient.getDeptChildBydept(user.getTenantId(), user.getDeptId());
		log.info("查询组织机构：{}",deptChildBydept);
		return deptChildBydept;
	}
	/**
	 * 修改
	 */
	@ApiLog("产品-列表-启用/禁用")
	@PostMapping("/updateProductState")
	@ApiOperationSupport(order = 40)
	@ApiOperation(value = "产品-列表-启用/禁用", notes = "传入productType")
	public R updateState(String productId,Integer state ) {
		ProductType one = productTypeService.getOne(new QueryWrapper<ProductType>().lambda().eq(ProductType::getProductId, productId));
		if(one == null){
			return R.fail("查不到对应的产品");
		}
		one.setUpdateTime(System.currentTimeMillis());
		one.setState(state);
		return R.status(productTypeService.updateById(one));
	}
}
